<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/14 0014
 * Time: 下午 2:06
 */

namespace App\Http\Common;

use App\Logic\Qiniu\Auth;
use App\Logic\Qiniu\Storage\UploadManager;
// 图片处理类
use App\Logic\Qiniu\Processing\ImageUrlBuilder;

class QiniuUpload {

    // 要上传的空间
    const bucket_beauty  = 'beauty';
    //外链默认域名
    const url = 'http://image.wyyys.cn/';

    private $auth;

    public function __construct()
    {
        $this->auth = new Auth(config('qiniu.accessKey') , config('qiniu.secretKey'));
    }


    /**
     * @param $files  多个文件
     * @return array
     */
    public function manyUpload($files)
    {
        $imgUrl = [];
        foreach($files as $name => $file)
        {
            $back = $this->upload($file);
            $imgUrl[$name] = $back['key'];
        }

        return $imgUrl;
    }

    /**
     * @param $path 上传图片
     * @return mixed
     * @throws \Exception
     */
    public function upload($file)
    {
        if(!$file->isValid()){
            return $file->getError();
        }
        $token = $this->auth->uploadToken($this::bucket_beauty);
        $realPath = $file->getRealPath(); //临时地址
        $newName = date('Ymd'). '_' . uniqid();
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $newName, $realPath);

        if ($err !== null) {
            return $err;
        } else {
            return $ret;
        }
    }

    /**
     * 缩略图链接拼接
     *
     * @param  string $url 图片链接
     * @param  int $mode 缩略模式
     * @param  int $width 宽度
     * @param  int $height 长度
     * @param  string $format 输出类型 [可选]
     * @param  int $quality 图片质量 [可选]
     * @param  int $interlace 是否支持渐进显示 [可选]
     * @param  int $ignoreError 忽略结果 [可选]
     * @return string
     * @link http://developer.qiniu.com/code/v6/api/kodo-api/image/imageview2.html
     * @author Sherlock Ren <sherlock_ren@icloud.com>
     */
    public function thumb($url,$mode = 1,$width = 200,$height = 200)
    {
        $imageUrlBuilder = new ImageUrlBuilder();
        $thumbLink = $imageUrlBuilder->thumbnail($url, $mode, $width, $height);
        return $thumbLink;
    }


}